import logging

from odoo import api, fields, models, _, tools
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)


class MESMrpRoutingWorkcenter(models.Model):
    _inherit = 'mrp.routing.workcenter'

    def upload_drill_mes_data(self):
        data_list = []
        data = {
            "docType": "PROD_DRILL_PARAM",
            "updateType": "UPDATE",
        }
        for record in self.drill_operation_ids:
            product_id = self.bom_id.product_tmpl_id
            if product_id.categ_id.code == 'BCP':
                layer_type = product_id.name.split('-')
                if len(layer_type)>1:
                    layer = layer_type[1]
                else:
                    layer = '0'
            else:
                layer = '0'
            drill_tolerance = record.drill_tolerance or ''
            drill_negative_tolerance = record.drill_negative_tolerance or ''
            # crm_id = product_id.customer_item_code_ids
            # if crm_id:
            #     crm_id = crm_id[0]
            dtl = {
                "org_code": "0001",
                "prod_code": product_id.default_code or '',  # 产品编号
                "version": product_id.versions or '',  # 产品版本（SKU）,  # 版本
                "layer_type": layer or '',  # 层别
                "tool_code": record.cutter_number or '',  # 刀号
                "linked_layer": record.connection_layer or '',  # 连接层别
                "drill_tape_ref": record.name or '',  # 钻带
                "final_hole_dia": record.finished_drill_solt_size or '',  # 成孔(mm)
                "slot_length": float(record.drill_solt_size or 0),  # slot长
                "tolerance_upper": float(drill_tolerance.replace('+', '') or 0),  # 正公差(mm)
                "tolerance_lower": float(drill_negative_tolerance.replace('-', '') or 0),  # 负公差(mm)
                "drill_diameter": float(record.drill_diameter or 0),  # 钻径(mm)
                "slot_machining_length": float(record.drill_length or 0),  # Slot加工长度(mm)
                "hole_type": record.n_pth or '',  # 孔类型(N/PTH)  Y：PTH，N：NPTH  示例值: Y N
                "machining_method": record.drill_method or '',  # 加工方式
                "unit_hole_count": float(record.pcs_hole_number or 0),  # PCS孔数
                "panel_set_hole_count": float(record.set_hole_number or 0),  # SET孔数
                "panel_hole_count": float(record.pnl_hole_number or 0),  # PNL孔数
                "hole_plugging_method": record.slot_type or '',  # 塞孔方式
                "depth_control_spec": record.depth_control or '',  # 控深
                "secondary_drill": record.second_drill or '',  # 二钻
                "remark": record.remark or '',
            }
            data_list.append(dtl)
        data['data'] = data_list
        return data if data_list else {}
